package com.shilei.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:  组合模式   树结构
 * @author: 81271
 * @date: 2020-04-18 11:22
 */
public class Main1 {
    public static void main(String[] args) {
        BranchNode root = new BranchNode("root");
        BranchNode chapter1 = new BranchNode("chapter1");
        BranchNode chapter2 = new BranchNode("chapter2");
        Node c11 = new LeafNode("c11");
        Node c12 = new LeafNode("c12");
        BranchNode section21 = new BranchNode("section21");
        Node c211 = new LeafNode("c211");
        Node c212 = new LeafNode("c212");
        root.add(chapter1);
        root.add(chapter2);
        chapter1.add(c11);
        chapter1.add(c12);
        chapter2.add(section21);
        section21.add(c211);
        section21.add(c212);

        tree(root, 0);


    }

    static void tree(Node node, int depth) {
        for (int i = 0; i < depth; i++) System.out.print("--");
        node.p();
        depth ++;

        if (node instanceof BranchNode)
            for (Node node1 : ((BranchNode)node).nodes) {
                tree(node1, depth);
            }

    }

}

abstract class Node {
    abstract void p();


}

class BranchNode extends Node{
    private String nodeName;
    List<Node> nodes = new ArrayList<>();

    BranchNode(String nodeName) {
        this.nodeName = nodeName;
    }

    void add (Node node) {
        nodes.add(node);
    }

    @Override
    void p() {
        System.out.println(nodeName);
    }
}

class LeafNode extends Node{
    private String nodeName;

    public LeafNode(String nodeName) {
        this.nodeName = nodeName;
    }

    @Override
    void p() {
        System.out.println(nodeName);
    }
}
